<template>
  <div class="order-detail-page">
    <el-card class="order-card" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span class="title">订单详情</span>
          <el-tag :type="getStatusType(order.status)">{{ getStatusText(order.status) }}</el-tag>
        </div>
      </template>
      
      <div v-if="!loading && order.id">
        <!-- 订单基本信息 -->
        <div class="order-info">
          <div class="info-item">
            <span class="label">订单编号：</span>
            <span class="value">{{ order.orderNo }}</span>
          </div>
          <div class="info-item">
            <span class="label">创建时间：</span>
            <span class="value">{{ formatDate(order.createdAt) }}</span>
          </div>
          <div class="info-item" v-if="order.paymentTime">
            <span class="label">支付时间：</span>
            <span class="value">{{ formatDate(order.paymentTime) }}</span>
          </div>
          <div class="info-item" v-if="order.completionTime">
            <span class="label">完成时间：</span>
            <span class="value">{{ formatDate(order.completionTime) }}</span>
          </div>
          <div class="info-item" v-if="order.cancelTime">
            <span class="label">取消时间：</span>
            <span class="value">{{ formatDate(order.cancelTime) }}</span>
          </div>
          <div class="info-item">
            <span class="label">支付方式：</span>
            <span class="value">{{ order.paymentMethod || '线下支付' }}</span>
          </div>
          <div class="info-item" v-if="order.remark">
            <span class="label">备注：</span>
            <span class="value">{{ order.remark }}</span>
          </div>
        </div>
        
        <!-- 商品信息 -->
        <div class="divider"></div>
        <div class="product-section">
          <h3>商品信息</h3>
          <div class="product-info">
            <img :src="product.productImageUrl && !product.productImageUrl.startsWith('http') ? '/images/product/' + product.productImageUrl : product.productImageUrl" 
            <div class="product-details"> </div> alt="商品图片" class="product-image" />
            
              <h4 class="product-name">{{ product.name }}</h4>
              <p class="product-description">{{ product.description }}</p>
              <p class="product-price">¥{{ order.price.toFixed(2) }}</p>
            </div>
          </div>
        </div>
        
        <!-- 用户信息 -->
        <div class="divider"></div>
        <div class="user-section">
          <h3>交易信息</h3>
          <div class="user-info">
            <div class="info-item">
              <span class="label">卖家：</span>
              <span class="value">{{ seller.username }}</span>
            </div>
            <div class="info-item" v-if="order.transactionLocation">
              <span class="label">交易地点：</span>
              <span class="value">{{ order.transactionLocation }}</span>
            </div>
          </div>
        </div>
        
        <!-- 订单评价 -->
        <div v-if="order.status === 2" class="divider"></div>
        <div v-if="order.status === 2" class="review-section">
          <h3>订单评价</h3>
          <div v-if="review.id" class="review-info">
            <div class="rating-info">
              <div class="rating-item">
                <span class="label">商品评分：</span>
                <el-rate v-model="review.ratingScore" disabled></el-rate>
              </div>
              <div class="rating-item">
                <span class="label">信誉评分：</span>
                <el-rate v-model="review.creditScore" disabled></el-rate>
              </div>
            </div>
            <div class="review-content">
              <p>{{ review.content }}</p>
            </div>
            <div v-if="review.images" class="review-images">
              <el-image 
                v-for="(img, index) in review.images.split(',')" 
                :key="index" 
                :src="img" 
                fit="cover"
                :preview-src-list="review.images.split(',')"
              ></el-image>
            </div>
            <div class="review-time">
              <p>评价时间：{{ formatDate(review.createdAt) }}</p>
            </div>
          </div>
          <div v-else-if="!order.isReviewed" class="no-review">
            <p>订单尚未评价</p>
            <el-button type="primary" @click="handleReview">立即评价</el-button>
          </div>
          <div v-else class="loading-review">
            <el-skeleton :rows="3" animated />
          </div>
        </div>
        
        <!-- 操作按钮 -->
        <div class="divider"></div>
        <div class="action-section">
          <el-button 
            v-if="order.status === 1" 
            type="primary" 
            @click="handleConfirmReceipt"
          >
            确认交易完成
          </el-button>
          <el-button
            v-if="order.status === 1"
            @click="handleCancel"
          >
            取消订单
          </el-button>
          <el-button @click="goBack">返回列表</el-button>
        </div>
      </div>
      
      <div v-else-if="!loading" class="not-found">
        <el-empty description="订单不存在或已被删除"></el-empty>
      </div>
    </el-card>
    
    <!-- 评价对话框 -->
    <el-dialog
      v-model="reviewDialogVisible"
      title="评价订单"
      width="40%"
    >
      <el-form :model="reviewForm" :rules="reviewRules" ref="reviewFormRef" label-width="100px">
        <el-form-item label="商品评分" prop="ratingScore">
          <el-rate v-model="reviewForm.ratingScore" :texts="['很差', '较差', '一般', '满意', '很满意']" show-text></el-rate>
        </el-form-item>
        <el-form-item label="卖家信誉评分" prop="creditScore">
          <el-rate v-model="reviewForm.creditScore" :texts="['很差', '较差', '一般', '满意', '很满意']" show-text></el-rate>
        </el-form-item>
        <el-form-item label="评价内容" prop="content">
          <el-input v-model="reviewForm.content" type="textarea" rows="4" placeholder="请输入您的评价内容"></el-input>
        </el-form-item>
        <el-form-item label="上传图片">
          <el-upload
            action="/api/upload"
            list-type="picture-card"
            :on-success="handleUploadSuccess"
            :on-remove="handleUploadRemove"
            :limit="3"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reviewDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReview" :loading="reviewLoading">
            提交评价
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 取消订单对话框 -->
    <el-dialog
      v-model="cancelDialogVisible"
      title="取消订单"
      width="30%"
    >
      <el-form :model="cancelForm" label-width="80px">
        <el-form-item label="取消原因">
          <el-select v-model="cancelForm.reason" placeholder="请选择取消原因" style="width: 100%">
            <el-option label="我不想要了" value="不想要了" />
            <el-option label="信息填写错误" value="信息填写错误" />
            <el-option label="与卖家协商一致" value="协商一致" />
            <el-option label="其他原因" value="其他原因" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="cancelForm.reason === '其他原因'" label="详细原因">
          <el-input v-model="cancelForm.detail" type="textarea" rows="3" placeholder="请填写详细原因"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCancel" :loading="cancelLoading">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useOrderStore } from '@/stores/order';
import { getOrderReview } from '@/api/order';

const route = useRoute();
const router = useRouter();
const orderStore = useOrderStore();
const orderId = ref(Number(route.params.id));

const loading = ref(true);
const order = ref<any>({});
const product = ref<any>({});
const seller = ref<any>({});
const review = ref<any>({});

// 取消订单相关
const cancelDialogVisible = ref(false);
const cancelLoading = ref(false);
const cancelForm = ref({
  reason: '不想要了',
  detail: ''
});

// 评价相关
const reviewDialogVisible = ref(false);
const reviewLoading = ref(false);
const reviewFormRef = ref<any>(null);
const uploadedImages = ref<string[]>([]);
const reviewForm = ref({
  ratingScore: 5,
  creditScore: 5,
  content: '',
  images: ''
});

const reviewRules = {
  ratingScore: [{ required: true, message: '请给商品评分', trigger: 'change' }],
  creditScore: [{ required: true, message: '请给卖家信誉评分', trigger: 'change' }],
  content: [{ required: true, message: '请输入评价内容', trigger: 'blur' }]
};

// 获取订单详情
const fetchOrderDetail = async () => {
  loading.value = true;
  try {
    const data = await orderStore.getOrder(orderId.value);
    if (data) {
      order.value = data;
      product.value = data.product || {};
      seller.value = data.seller || {};
      
      // 如果订单已完成并已评价，获取评价信息
      if (data.status === 2 && data.isReviewed) {
        fetchOrderReview();
      }
    } else {
      ElMessage.error('获取订单详情失败');
    }
  } catch (error) {
    console.error('获取订单详情失败:', error);
    ElMessage.error('获取订单详情失败');
  } finally {
    loading.value = false;
  }
};

// 获取商品展示图片的方法，处理不同的图片字段情况
const getProductImageUrl = (product) => {
    // 1. 检查是否有productImageUrl字段
    if (product.productImageUrl) {
        // 判断是完整URL还是文件名
        return typeof product.productImageUrl === 'string' && product.productImageUrl.startsWith('http')
            ? product.productImageUrl 
            : `/images/product/${product.productImageUrl}`;
    }
    
    // 2. 检查是否有images数组且有内容
    if (product.images && product.images.length > 0) {
        const firstImage = product.images[0];
        // 判断是完整URL还是文件名
        return typeof firstImage === 'string' && firstImage.startsWith('http')
            ? firstImage
            : `/images/product/${firstImage}`;
    }
    
    // 3. 检查其他可能的图片字段
    const imageField = product.image || product.coverImage || product.imgUrl;
    if (imageField) {
        return typeof imageField === 'string' && imageField.startsWith('http')
            ? imageField
            : `/images/product/${imageField}`;
    }
    
    // 4. 都没有则返回默认占位图
    return `https://api.dicebear.com/7.x/shapes/svg?seed=${product.id || 'product'}&backgroundColor=007AFF`;
}
// 获取订单评价
const fetchOrderReview = async () => {
  try {
    const response = await getOrderReview(orderId.value);
    if (response.code === 200) {
      review.value = response.data;
    }
  } catch (error) {
    console.error('获取订单评价失败:', error);
  }
};

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
};

// 获取状态文本
const getStatusText = (status: number) => {
  const statusMap: Record<number, string> = {
    1: '待交易',
    2: '已完成',
    3: '已取消',
    4: '待评价'
  };
  return statusMap[status] || '未知状态';
};

// 获取状态对应的标签类型
const getStatusType = (status: number) => {
  const typeMap: Record<number, string> = {
    1: 'primary',
    2: 'success',
    3: 'info'
  };
  return typeMap[status] || '';
};

// 返回订单列表
const goBack = () => {
  router.push('/user/orders');
};

// 确认收货
const handleConfirmReceipt = async () => {
  try {
    await ElMessageBox.confirm(
      '确认已收到商品吗？',
      '确认收货',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    const result = await orderStore.confirmReceipt(orderId.value);
    if (result) {
      ElMessage.success('确认收货成功');
      fetchOrderDetail();
    } else {
      ElMessage.error('确认收货失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认收货失败:', error);
      ElMessage.error('确认收货失败');
    }
  }
};

// 取消订单
const handleCancel = () => {
  cancelForm.value = { reason: '不想要了', detail: '' };
  cancelDialogVisible.value = true;
};

// 确认取消订单
const confirmCancel = async () => {
  cancelLoading.value = true;
  try {
    const reason = cancelForm.value.reason === '其他原因' 
      ? cancelForm.value.detail 
      : cancelForm.value.reason;
      
    const result = await orderStore.cancelOrder(orderId.value, reason);
    if (result) {
      ElMessage.success('订单已取消');
      cancelDialogVisible.value = false;
      fetchOrderDetail();
    } else {
      ElMessage.error('取消订单失败');
    }
  } catch (error) {
    console.error('取消订单失败:', error);
    ElMessage.error('取消订单失败');
  } finally {
    cancelLoading.value = false;
  }
};

// 评价订单
const handleReview = () => {
  reviewForm.value = {
    ratingScore: 5,
    creditScore: 5,
    content: '',
    images: ''
  };
  uploadedImages.value = [];
  reviewDialogVisible.value = true;
};

// 上传图片成功回调
const handleUploadSuccess = (response: any) => {
  uploadedImages.value.push(response.data.url);
};

// 移除上传图片
const handleUploadRemove = (file: any) => {
  const url = file.response?.data?.url;
  if (url) {
    const index = uploadedImages.value.indexOf(url);
    if (index !== -1) {
      uploadedImages.value.splice(index, 1);
    }
  }
};

// 提交评价
const submitReview = async () => {
  if (!reviewFormRef.value) return;
  
  try {
    await reviewFormRef.value.validate();
    
    reviewLoading.value = true;
    
    // 组合图片URL
    reviewForm.value.images = uploadedImages.value.join(',');
    
    const result = await orderStore.createOrderReview(orderId.value, reviewForm.value);
    if (result) {
      ElMessage.success('评价提交成功');
      reviewDialogVisible.value = false;
      fetchOrderDetail();
    } else {
      ElMessage.error('提交评价失败');
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('提交评价失败:', error);
      ElMessage.error('提交评价失败');
    }
  } finally {
    reviewLoading.value = false;
  }
};

onMounted(() => {
  fetchOrderDetail();
});
</script>

<style scoped>
.order-detail-page {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.order-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.order-info {
  margin-bottom: 20px;
}

.info-item {
  margin-bottom: 10px;
  display: flex;
}

.label {
  width: 100px;
  color: #606266;
  font-size: 14px;
}

.value {
  color: #303133;
  font-size: 14px;
}

.divider {
  height: 1px;
  background-color: #ebeef5;
  margin: 20px 0;
}

.product-section,
.user-section,
.review-section {
  margin-bottom: 20px;
}

h3 {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 16px;
}

.product-info {
  display: flex;
  align-items: flex-start;
}

.product-image {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 4px;
  margin-right: 20px;
}

.product-details {
  flex: 1;
}

.product-name {
  margin: 0 0 10px;
  font-size: 16px;
  color: #303133;
}

.product-description {
  margin: 0 0 10px;
  font-size: 14px;
  color: #606266;
  line-height: 1.5;
}

.product-price {
  color: #F56C6C;
  font-size: 18px;
  font-weight: 600;
  margin: 0;
}

.user-info {
  padding: 10px 0;
}

.review-info {
  background-color: #f5f7fa;
  padding: 16px;
  border-radius: 4px;
}

.rating-info {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 16px;
}

.rating-item {
  display: flex;
  align-items: center;
}

.review-content {
  margin-bottom: 16px;
  line-height: 1.6;
}

.review-images {
  display: flex;
  gap: 10px;
  margin-bottom: 16px;
  flex-wrap: wrap;
}

.review-images .el-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  cursor: pointer;
}

.review-time {
  color: #909399;
  font-size: 12px;
  text-align: right;
}

.no-review {
  text-align: center;
  padding: 20px 0;
}

.not-found {
  padding: 40px 0;
}

.action-section {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
}
</style> 